import Axios from 'axios'
import {Message} from 'iview'
import {setToken, getToken, removeToken} from '@/libs/util'
import config from '@/config'

class httpRequest {
  constructor() {
    this.options = {
      method: '',
      url: ''
    }
    this.queue = {}
  }

  destroy(url) {
    delete this.queue[url]
    const queue = Object.keys(this.queue)
    return queue.length
  }


  interceptors(instance, url) {

    // 请求拦截器
    instance.interceptors.request.use(config => {
      if (getToken()) {
        config.headers['Authorization'] = getToken()
      }
      return config
    }, error => {
      return Promise.reject(error)
    })

    // 响应拦截器
    instance.interceptors.response.use((res) => {
        let {data, headers} = res
        this.destroy(url)

        if (!(data instanceof Blob)) {  // 不是二进制对象
          if (data.code !== 200) {
            // 后端服务在个别情况下回报201，待确认
            if (data.message) Message.error(data.message)
            return false
          }
        }

        // 新的token
        if (headers.authorization) {
          setToken(headers.authorization)
        }

        return data
      }, (error) => {
        if (error.response) {
          let res = error.response;
          let status = res.status;
          let {message} = res.data;

          // 回报401
          if (status === 401) {
            removeToken()
            Message.error(message || '请登录后继续操作(HTTP:401)')
            window.location.href = config.loginUrl
            return Promise.reject(error)
          }

          // 回报404
          if (status === 404) {
            Message.error(message || '请求资源不存在(HTTP:404)')
            return Promise.reject(error)
          }

          // 其他回报
          Message.error(message || '服务器内部错误')

        } else {
          Message.error('服务器连接失败')
        }

        return Promise.reject(error)
      }
    )
  }

  // 创建实例
  create() {
    let conf = {
      headers: {
        'Content-Type': 'application/json; charset=utf-8',
        // 'X-URL-PATH': location.pathname
      },
      withCredentials: true,
    }
    return Axios.create(conf)
  }

  // 请求实例
  request(options) {
    let instance = this.create()
    this.interceptors(instance, options.url)
    options = Object.assign({}, options)
    this.queue[options.url] = instance
    return instance(options)
  }
}

export default httpRequest
